package com.lily.ssm.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.lily.ssm.model.ProductClass;
import com.lily.ssm.service.ProductClassService;



@Controller
public class ProductClassController {
	
	@Autowired
	private ProductClassService productClassService;
	
	@RequestMapping(value="/list.do")
	public String list(Model model){
		List<ProductClass> productClasses = productClassService.getList();
		List<ProductClass> productSmallClasses = new ArrayList<>();
		Map<Integer,ProductClass> smallClassMap = new HashMap<>();
		for (ProductClass productClass : productClasses) {
			productSmallClasses = productClassService.smaClass(productClass.getClassId());
			for (ProductClass productSmallClass : productSmallClasses) {
				smallClassMap.put(productSmallClass.getClassId(), productSmallClass);
			}
		}
		model.addAttribute("productClasses", productClasses);
		model.addAttribute("smallClassMap", smallClassMap);
		return "manage/productClass";
	}
	
	@RequestMapping(value="/updateProduct.do",method=RequestMethod.GET)
	public String updateProduct(int classId,Model model){
		List<ProductClass> productClasses = productClassService.getList();
		ProductClass productClass = productClassService.getClass(classId);
		model.addAttribute("productClass", productClass);
		model.addAttribute("productClasses", productClasses);
		return "manage/productClass-modify";
	}
	
	@RequestMapping(value="/updateProduct",method=RequestMethod.POST)
	public String updateProduct(ProductClass productClass){
		productClassService.updateProduct(productClass);
		return "redirect:/list.do";
	}
	
	@RequestMapping("/deleteProduct.do")
	public String detete(int classId){
		productClassService.deleteProduct(classId);
		return "redirect:/list.do";
	}
	
	@RequestMapping(value="/addProduct.do",method=RequestMethod.GET)
	public String addProduct(Model model){
		List<ProductClass> productClasses = productClassService.getList();
		for (ProductClass productClass : productClasses) {
			System.out.println(productClass.getParentId());
		}
		model.addAttribute("productClasses", productClasses);
		return "manage/productClass-add";
	}
	
	@RequestMapping(value="/addProduct.do",method=RequestMethod.POST)
	public String addProduct(ProductClass productClass,String parentId){
		productClassService.insertProductClass(productClass);
		System.out.println(productClass);
		System.out.println(parentId);
		return "redirect:/list.do";
	}
}
